<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search
      ref="customSearchRef"
      v-slot="{ params }"
      :default-params="{ adCode: [], signTime: [], contractStartTime: [], contractEndTime: [] }"
      @submit="handleInitTable"
    >
      <t-col :span="3">
        <t-form-item label="订单编号" name="orderNo">
          <t-input v-model:value="params.orderNo" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="订单类型" name="orderType">
          <t-select
            v-model:value="params.orderType"
            :options="dictionaryStore.get('decoration_order_type')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="合同编号" name="contractNo">
          <t-input v-model:value="params.contractNo" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户名称" name="customerName">
          <t-input v-model:value="params.customerName" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="手机号码" name="phone">
          <t-input v-model:value="params.phone" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="归属城市" name="adCode">
          <t-cascader
            v-model:value="params.adCode"
            :options="city.tree"
            :keys="{ label: 'name', value: 'adcode', children: 'districts' }"
            placeholder=""
            filterable
            clearable
            check-strictly
            value-type="full"
            @change="(value: any) => handleAdCodeChange(value, params)"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyId">
          <t-select v-model:value="params.propertyId" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="审批状态" name="approvalStatus">
          <t-select
            v-model:value="params.approvalStatus"
            :options="dictionaryStore.get('bpm_task_status')"
            clearable
            filterable
            placeholder=""
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="创建时间" name="createTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.createTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="签约时间" name="signTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.signTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="合同开工时间" name="contractStartTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.contractStartTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="合同完工时间" name="contractEndTime">
          <t-date-range-picker
            allow-input
            v-model:value="params.contractEndTime"
            clearable
            enable-time-picker
            placeholder=" "
            style="width: 100%"
          />
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table
      ref="customTableRef"
      row-key="id"
      :columns="columns"
      :api="contractListCRUD.page"
      column-controller-key="contractList"
    >
      <!-- <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-button
            v-permission="['decoration:contract:create']"
            @click="handleOpenDialog('create', { files: [], installmentList: [] })"
          >
            新建合同
          </t-button>
        </div>
      </template> -->
      <template #orderType="{ row }">
        {{ dictionaryStore.analysis('decoration_order_type', row.orderType) }}
      </template>
      <template #adCode="{ row }">
        {{ analysisCity(row) }}
      </template>
      <template #propertyId="{ row }">
        {{ propertyInfoList.find((item) => item.id === row.basicOrder.propertyId)?.name }}
      </template>
      <template #reporterName="{ row }">
        {{ userStore.getUserNameById(row.basicOrder.creator) }}
      </template>
      <template #saleName="{ row }">
        {{ userStore.getUserNameById(row.basicOrder.saleId) }}
      </template>
      <template #designerName="{ row }">
        {{ userStore.getUserNameById(row.designOrder.designerId) }}
      </template>
      <template #createTime="{ row }">
        {{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #signTime="{ row }">
        {{ dayjs(row.signTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #contractStartTime="{ row }">
        {{ dayjs(row.contractStartTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #contractEndTime="{ row }">
        {{ dayjs(row.contractEndTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- 查看订单 -->
          <view-order :id="row.orderId" />
          <t-link
            v-permission="['decoration:contract:query']"
            theme="primary"
            @click="handleOpenDialog('read', { id: row.id })"
          >
            详情
          </t-link>
          <t-link
            v-permission="['decoration:contract:update']"
            theme="primary"
            @click="handleOpenDialog('update', { id: row.id })"
          >
            编辑
          </t-link>
          <t-popconfirm content="确认要删除该项吗？" @confirm="handleDelete({ id: row.id })">
            <t-link v-permission="['decoration:contract:delete']" theme="danger"> 删除 </t-link>
          </t-popconfirm>
        </t-space>
      </template>
    </custom-table>
    <!-- 自定义对话框 -->
    <contract-dialog ref="customDialogRef" @request-success="handleDialogRequestSuccess" />
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'FinanceContract',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin, TableCol } from 'tdesign-vue-next';
import { onMounted, ref, useTemplateRef } from 'vue';

import { propertyManageCRUD } from '@/api/config/property';
import { contractListCRUD } from '@/api/finance/contract';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import ViewOrder from '@/pages/order/details/components/ViewOrder.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import city from '@/utils/city';

import ContractDialog from './components/ContractDialog.vue';

// 用户仓库
const userStore = useUserStore();
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'basicOrder.orderNo', title: '订单编号', width: 300 },
  { colKey: 'orderType', title: '订单类型', width: 100 },
  { colKey: 'contractNo', title: '合同编号', width: 300 },
  { colKey: 'basicOrder.customerName', title: '客户名称 ', width: 100 },
  { colKey: 'basicOrder.phone', title: '手机号码', width: 130 },
  { colKey: 'basicOrder.adCode', title: '归属城市', width: 250, cell: 'adCode' },
  { colKey: 'basicOrder.propertyId', title: '楼盘名称', width: 200, cell: 'propertyId' },
  { colKey: 'basicOrder.address', title: '详细地址', width: 100 },
  { colKey: 'approvalStatus', title: '审批状态', width: 120 },
  { colKey: 'reporterName', title: '上报人', width: 120 },
  { colKey: 'saleName', title: '客服', width: 100 },
  { colKey: 'designerName', title: '设计师', width: 120 },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'signTime', title: '签约时间', width: 180 },
  { colKey: 'contractStartTime', title: '合同开工时间', width: 180 },
  { colKey: 'contractEndTime', title: '合同完工时间', width: 180 },
  { colKey: 'operation', title: '操作', width: 150, fixed: 'right' },
];
// 处理初始化表格
const handleInitTable = () => {
  const params = { ...customSearchRef.value.params };
  if (!params.adCode || !params.adCode.length) {
    delete params.provinceCode;
    delete params.cityCode;
    delete params.areaCode;
  }
  customTableRef.value.initTable(params);
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
onMounted(() => {
  handleInitTable();
});
// 自定义对话框ref
const customDialogRef = useTemplateRef('customDialogRef');
// 处理打开对话框
const handleOpenDialog = (mode: 'create' | 'read' | 'update', params: Record<string, any>) => {
  customDialogRef.value.open(mode, params);
};
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 处理删除
const handleDelete = (params: Record<string, any>) => {
  contractListCRUD
    .delete(params)
    .then(() => {
      MessagePlugin.success('删除成功');
      handleRefreshTable();
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
// 处理归属城市改变
const handleAdCodeChange = (value: string[], params: Record<string, any>) => {
  params.provinceCode = value[0] || '';
  params.cityCode = value[1] || '';
  params.areaCode = value[2] || '';
};
// 解析城市
const analysisCity = (row: Record<string, any>) => {
  let result = '';
  if (row.basicOrder.provinceCode) {
    result += city.list.find((item) => item.adcode === row.basicOrder.provinceCode).name;
  }
  if (row.basicOrder.cityCode) {
    result += ` / ${city.list.find((item) => item.adcode === row.basicOrder.cityCode).name}`;
  }
  if (row.basicOrder.areaCode) {
    result += ` / ${city.list.find((item) => item.adcode === row.basicOrder.areaCode).name}`;
  }
  return result;
};
</script>
